<?php
/**
 * Extract info of IMDB site
 *
 *
 * LICENSE: Some license information
 *
 * phpMMB version: 0.0.1
 *
 * $copyright  2007 SaWey
 * $license    GNU GPL v3.
 * $URL: http://www.sawey.be/phpMyMovieBox $
 * $Revision: 6 $
 * $LastChangedBy: sander.weyens $
 * $Date: 2008-01-14 22:20:38 +0000 (Mon, 14 Jan 2008) $
 */
/**********************************\
||================================||
||          Originaly             ||
||        IMDbFetch v0.3          ||
||     IMDbFetch.class.php        ||
||              |                 ||
||          - class -             ||
||   by teo rusu                  ||
||   spinicrus@gmail.com          ||
||   http://- :) not yet, no time ||
||                                ||
||================================||
\\************************/////////
/////////
/////////
//
ini_set("max_execution_time","20000");
ini_set("max_input_time","20000");
//define imdb fetch class:
class IMDB
{
	//
	var $addressLink;
	var $id;
	var $name;
	var $year;
	var $director;
	var $writer;
	var $genre;
	var $rating;
	var $runtime;
	var $comment;
	var $poster_link;
	//new vars
	var $color;
	var $country;
	var $language;
	var $plot;
	var $tagline;
	var $stars;
	var $aka;
	var $awards;
	var $cast;
	var $imdb_searchform = 'http://imdb.com/find?q=';
	var $fullcredits = false; //if we want to add the whole cast, set to true
	var $save_image = true;
	//
	function IMDB() 
	{
	}
	
	function searchTitles($imdb_search_title) 
    { 
		if(($imdb_site_result = @file_get_contents($this->imdb_searchform . urlencode($imdb_search_title))) != false)
		{ 
			if(preg_match('/<title>IMDb  Search<\/title>/i', $imdb_site_result))
			{
				if (preg_match('/No Matches/i', $imdb_site_result)) 
				{ 
					//nothing found 
					return false;                 
				} 
				else 
				{ 
					if (preg_match_all('/<a href="\/title\/(tt\d{1,8})\/">([^<]+)<\/a> (\(\d{1,5}\))/',$imdb_site_result,$results, PREG_SET_ORDER )) 
					{ 
						return $results; 
					} 
				} 
			}
			else
			{
				//only 1 result, send redirect
				preg_match('/tt\d{1,8}/', $imdb_site_result, $result);
				header('Location: ?page=admin&sub=mymovies&f=add_movie_lookup&add=' . $result[0]);
			}
		}
		else
		{
			return false;
		}
    } 
	
	function getMovieInfo($IMDBlink)
	{
		if (substr($IMDBlink, strlen($IMDBlink)-1, 1) != '/') 
		{
			$IMDBlink = $IMDBlink.'/';
		}
		$this->addressLink = $IMDBlink;
		
		if(($searchPage = @file_get_contents($this->addressLink)) == false)
		{
			return false;
		}
		//
		//IMDB ID:
		//
		$imdbIDStartTag    = 'title/tt';
		$imdbIDStartTagPos = strpos($this->addressLink,$imdbIDStartTag);
		$imdbIDEndTag      = '/';
		$imdbIDEndTagPos   = strpos($this->addressLink,$imdbIDEndTag,$imdbIDStartTagPos);
		$imdbID = substr($this->addressLink,$imdbIDStartTagPos+strlen($imdbIDStartTag),$imdbIDEndTagPos-$imdbIDStartTagPos-strlen($imdbIDStartTag)+2);
		$this->id = cleanString($imdbID);
		//
		//IMDB NAME:
		//
		$imdbNameStartTag = '<div id="tn15title">';
		$imdbNameEndTag   = '<span>';
		$this->name = cleanString(strip_tags(extractStringFromString($searchPage, $imdbNameStartTag, $imdbNameEndTag)));
		//
		//IMDB YEAR:
		//
		$imdbYearStartTag = '<span>(<a href="/Sections/Years/';
		$imdbYearEndTag   = '">';
		$this->year = cleanString(strip_tags(extractStringFromString($searchPage, $imdbYearStartTag, $imdbYearEndTag)));
		//
		//IMDB DIRECTED BY:
		//
		preg_match('/<h5>(?:Director:|Directors:)<\/h5>\s*([^\n]+)/', $searchPage, $result);
		$this->director = str_replace('<br/>', ' ', $result[1]);
		$this->director = cleanString(strip_tags($this->director));
		//
		//IMDB WRITING CREDITS:
		//
		preg_match('/<h5>(?:Writer:|Writers:|Writers \<a href="\/wga">\(WGA\)<\/a>:)<\/h5>\s*([^\n]+)/', $searchPage, $result);
		$this->writer = str_replace('<br/>', ' ', $result[1]);
		$this->writer = cleanString(strip_tags($this->writer));
		//
		//IMDB GENRE:
		//
		$imdbGenreStartTag = '<h5>Genre:</h5>';
		$imdbGenreEndTag   = '</div>';
		$this->genre = cleanString(strip_tags(extractStringFromString($searchPage, $imdbGenreStartTag, $imdbGenreEndTag)));
		//
		//IMDB RATING:
		//
		$imdbRatingStartTag = '<b>User Rating:</b>';
		$imdbRatingEndTag   = '</small>';
		$this->rating = cleanString(strip_tags(extractStringFromString($searchPage, $imdbRatingStartTag, $imdbRatingEndTag)));
		//
		//IMDB RUNTIME:
		//
		$imdbRuntimeStartTag = '<h5>Runtime:</h5>';
		$imdbRuntimeEndTag   = '</div>';
		$this->runtime = cleanString(strip_tags(extractStringFromString($searchPage, $imdbRuntimeStartTag, $imdbRuntimeEndTag)));
		//
		//IMDB COLOR
		//
		preg_match('/<a href="\/List\?color-info=.+">(.+)<\/a>/', $searchPage, $result);
		$this->color = trim($result[1]);
		//
		//IMDB COUNTRY
		//
		preg_match('/<a href="\/Sections\/Countries\/([a-z]+)\/">/i', $searchPage, $result);
		$this->country = trim($result[1]);
		//
		//IMDB LANGUAGE
		//
		preg_match('/<a href="\/Sections\/Languages\/([a-z]+)\/">/i', $searchPage, $result);
		$this->language = trim($result[1]);
		//
		//IMDB PLOT 
		//
		preg_match('/Plot .{7}:\<\/h5>([^<]+)(\<a class="tn15more inline" href="\/rg\/title-tease\/plotsummary|\<a class="tn15more inline" href="\/title\/tt[0-9]{1,8}\/plotsummary|\<\/div>)/', $searchPage, $result);
		$this->plot = trim($result[1]);
		//
		//IMDB TAGLINE
		//
		preg_match('/Tagline:\<\/h5>([^<]+)(\<a class="tn15more inline" href="\/title\/tt[0-9]{1,8}\/taglines|\<a class="tn15more inline" href="\/rg\/title-tease\/taglines|\<\/div>)/', $searchPage, $result);
		$this->tagline = trim($result[1]);
		//
		//IMDB STARS
		//
		preg_match('/<b>([0-9]{1,2}\.[0-9]{1,2})\/10<\/b>/', $searchPage, $result);
		$this->stars = trim($result[1]);
		//
		//IMDB AKA
		//
		preg_match('/Also Known As:<\/h5>([^<]+)<br>/', $searchPage, $result);
		$this->aka = trim($result[1]);
		//
		//IMDB AWARDS
		//
		preg_match('/(?:Awards:|Award:)<\/h5>([^<]+)/', $searchPage, $result);
		$this->awards = trim($result[1]);
		//
		//IMDB COMMENT:
		//
		$imdbCommentStartTag = ' people found the following comment useful:-';
		$imdbCommentEndTag   = 'Was the above comment useful to you?';
		$this->comment = strip_tags(extractStringFromString($searchPage, $imdbCommentStartTag, $imdbCommentEndTag),'<br/> <br><p>');
		//
		//IMDB IMAGE:
		//
		preg_match('/<a name="poster".+title=".+">(.+)<\/a>/', $searchPage, $html_link);
		preg_match('/ src="([^"]+)/', $html_link[1], $result);
		$this->poster_link = trim($result[1]);
		//
		if ($this->poster_link === false) 
		{
			$this->poster_link = '- not available at the moment -';
		}
		if($this->save_image)
		{
			$imdbPosterURLStartTag = '<img border="0" alt="'.$this->name.'" title="'.$this->name.'" src="';
			$imdbPosterURLEndTag   = '" height="';
			$imdbPosterURL = cleanString(extractStringFromString($searchPage, $imdbPosterURLStartTag, $imdbPosterURLEndTag));

			if($this->poster_link != '- not available at the moment -' && ($instr = @fopen($imdbPosterURL,"rb")))
			{
				$ext = getExt($imdbPosterURL);
				$img_name = 'images/posters/' . $this->id . '.' . $ext;
				$img_file = fopen($img_name, 'w');
				$imdbImageData = '';
				while (!feof($instr)) {
					fwrite($img_file, fread($instr, 8192));
				}
				fclose($instr);
				fclose($img_file);
				$this->poster_image_link = $img_name;
			}
			else
			{	
				//could not grab image, get the link from IMDb
				$this->poster_image_link = '- not available at the moment -';
			}
		}
		//
		//CAST:
		//
		if($this->fullcast)
		{
			$imdbCastStartTag = '<table class="cast">';
			$imdbCastEndTag   = '</table>';
			$imdbCastString = extractStringFromString(file_get_contents($this->addressLink . 'fullcredits'), $imdbCastStartTag, $imdbCastEndTag);
		}
		else
		{
			$imdbCastStartTag = '<h3>Cast</h3>';
			$imdbCastEndTag   = '</table>';
			$imdbCastString = extractStringFromString($searchPage, $imdbCastStartTag, $imdbCastEndTag);
		}
		
		preg_match_all('/<td class="nm">(<a href="\/name\/nm.{0,8}">|)([^<]+)(<\/a>|)/', $imdbCastString, $temp_names, PREG_SET_ORDER);
		preg_match_all('/<td class="char">(<a href="\/character\/ch.{0,8}">|)([^<]+)(<\/a>|)/', $imdbCastString, $temp_chars, PREG_SET_ORDER);
		//merge the two arrays

		if(is_array($temp_names))
		{
			foreach($temp_names as $key => $name)
			{
				$cast[$key]['name'] = $name[2];
				$cast[$key]['character'] = $temp_chars[$key][2];
			}
		}
		$this->cast = $cast;
		
		//tell we are done
		return true;
	}
	//function to display poster image:
	function getPoster() 
	{
		if($this->save_image)
		{
			//take the link to this server
			if($this->poster_image_link == '- not available at the moment -')
			{
				$poster['html'] = '<img id="poster_image" src="images/posters/no_poster.jpg" alt="' . $this->name . '"/>';
				$poster['url'] = 'images/posters/no_poster.jpg';
			}
			else
			{
				$poster['html'] = '<img src="' . $this->poster_image_link . '" alt="' . $this->name . '"/>';
				$poster['url'] = $this->poster_image_link;
			}
		}
		else
		{
			//take the imdb link
			if($this->poster_link == '- not available at the moment -')
			{
				$poster['html'] = '<img id="poster_image" src="images/posters/no_poster.jpg" alt="' . $this->name . '"/>';
				$poster['url'] = 'images/posters/no_poster.jpg';
			}
			else
			{
				$poster['html'] = '<img src="' . $this->poster_link . '" alt="' . $this->name . '"/>';
				$poster['url'] = $this->poster_link;
			}
		}
		return $poster;
	}
}
	//define some functions we need:
	function cleanString($imputString) {
		$whatToCleanArray = array(chr(13), chr(10), chr(13).chr(10), chr(10).chr(13), "\n", "  ", "   ", "    ", "\n\n", "\n\r", "s (WGA):", "s:", "...", "more");
		$cleanWithArray = array("","","","","","","","","","");
		$cleaned = str_replace($whatToCleanArray,$cleanWithArray,$imputString);
		$cleaned = trim($cleaned);
		return $cleaned;
	}
	//
	function getExt($filename) {
		return substr(strrchr($filename,"."),1);
	}
	//
	function extractStringFromString($string, $start, $end) {
		//
		$startPos = strpos($string,$start);
		$stringEndTagPos = strpos($string,$end,$startPos);
		$stringBetween = substr($string,$startPos+strlen($start),$stringEndTagPos-$startPos-strlen($start));
		//
		if (strlen($stringBetween) != 0) {
			//
			return $stringBetween;
			return true;
		}
		else {
			//
			return false;
		}
	}
	//
	function strpos_reverse_way($string,$charToFind,$relativeChar) {
		//
		$relativePos = strpos($string,$relativeChar);
		$searchPos = $relativePos;
		$searchChar = '';
		//
		while ($searchChar != $charToFind) {
			$newPos = $searchPos-1;
			$searchChar = substr($string,$newPos,strlen($charToFind));
			$searchPos = $newPos;
		}
		//
		if (!empty($searchChar)) {
			//
			return $searchPos;
			return TRUE;
		}
		else {
			return FALSE;
		}
		//
	}
?>